import { describe } from '$lib';
import { Clock } from '$lib/clock';
import { Collision, Glyph, Impassable } from '$lib/components';
import { log } from '$lib/log';
import { Diggable, Passage } from './ground';
import { getPos3, landscapeAt, move, onTile } from '$lib/pos3';
import { decode, encode } from '$lib/util';
import { addComponent, hasComponent } from '$lib/ecs';

export const DigAndMoveAction = (dx, dy, dz, delay) => (world, e) => {
  const { x, y, z } = getPos3(e);
  const x1 = x + dx;
  const y1 = y + dy;
  const z1 = z + dz;
  const landscape = landscapeAt(world, x1, y1, z1);
  return {
    error: false,
    action: () => {
      Clock.time[e] += delay;
      if (!hasComponent(world, Diggable, landscape)) {
        log("Trying to dig undiggable!");
        return;
      }
      if (hasComponent(world, Passage, landscape)) {
        log("No need to dig through a passage");
      }
      addComponent(world, Passage, landscape);
      Glyph.color[landscape] = encode(`color-mix(in lch, ${decode(Glyph.color[landscape])} 50%, #00f1)`);
      const col = onTile(world, x1, y1, z1).filter(c =>
        (hasComponent(world, Collision, c) || hasComponent(world, Impassable, c))
        && !hasComponent(world, Passage, c));
      if (col.length === 0) {
        move(world, e, x1, y1, z1);
      } else {
        const tgt = col[0];
        log(`${describe(world, e)} bumps into ${describe(world, tgt)}`);
      }
    },
  };
};
